package cn.buyclss.microapp.exception;

import cn.buyclss.microapp.entity.support.RespCode;
import cn.buyclss.microapp.entity.support.RespResult;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @author: Cecurio
 * @create: 2019-02-10 21:06
 * 全局异常处理
 **/
@ControllerAdvice
public class GlobalExceptionHandler {
    @Value("${spring.profiles.active}")
    private String env;

    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    public RespResult authenticationException(AuthenticationException e) {
        // 开发环境下打印 异常栈 信息，方便调试
        if ("dev".equals(env)) {
            e.printStackTrace();
        }
        RespResult res = new RespResult();
        res.setCode(RespCode.FAILURE);
        res.setErrMsg(e.getMessage());
        return res;
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public RespResult runtimeExceptionHandler(RuntimeException e) {
        // 开发环境下打印 异常栈 信息，方便调试
        if ("dev".equals(env)) {
            e.printStackTrace();
        }
        RespResult res = new RespResult();
        res.setCode(RespCode.FAILURE);
        res.setErrMsg(e.getMessage());
        return res;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public RespResult exceptionHandler(Exception e) {
        // 开发环境下打印 异常栈 信息，方便调试
        if ("dev".equals(env)) {
            e.printStackTrace();
        }
        RespResult res = new RespResult();
        res.setCode(RespCode.FAILURE);
        res.setErrMsg(e.getMessage());
        return res;
    }
}
